package com.tomcat.mesos.tomcat.impl;

import com.tomcat.mesos.Constants;
import com.tomcat.mesos.Orders;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.KeeperException;

import java.util.List;

/**
 * Tomcat 容器实例管理
 *
 * @author Rayn on 2015/12/22 9:49
 * @email liuwei412552703@163.com
 */
public class TomcatInstanceManager
{
    public void status(CuratorFramework zookeeper) throws KeeperException.NoNodeException
    {
        List<String> ns = zookeeper.getChildren().forPath(Constants.ZK_PREFIX);
        for(String namespace : ns)
        {
            System.out.println("[namepace=" + namespace + "]");
            final String nsZnode = ZKPaths.makePath(Constants.ZK_PREFIX, namespace);
            final List<String> apps = zookeeper.getChildren()
                    .forPath(nsZnode);
            for(String app : apps)
            {
                System.out.println(" " + app);
                final String appZnode = ZKPaths.makePath(nsZnode, app);
                final List<String> instances =
                        zookeeper.getChildren().forPath(appZnode);
                for (String instance : instances)
                {
                    if (instance.startsWith("slave"))
                    {
                        final String slaveZnode = ZKPaths.makePath(appZnode, instance);
                        final byte[] bytes = zookeeper.getData().forPath(slaveZnode);
                        System.out.println("  " + new String(bytes, Charsets.UTF_8));
                    }
                }
            }
        }
    }

    /**
     * 启动应用
     */
    public static void start(CuratorFramework zookeeper) throws KeeperException.NoNodeException {

    }

    /**
     * 添加tomcat 实例
     */
    public static void add(CuratorFramework zookeeper) throws KeeperException.NoNodeException
    {

        final DistributedQueue<Integer> queue = Orders.getDistributedQueue(zookeeper, Constants.ZK_ + "/" + ns + "/" + war + Constants.ORDERS);
        queue.start();
        queue.put(count);
    }

    /**
     * 停止一个 tomcat 实例
     * @param zookeeper
     */
    public static void stop(CuratorFramework zookeeper) throws KeeperException.NoNodeException
    {
        zookeeper.delete().deletingChildrenIfNeeded().forPath(Constants.ZK_PREFIX);
    }
}
